package kr.pe.johnkim.app.mobile.rest.dao;

import kr.pe.johnkim.app.domain.MyHistoryMember;
import kr.pe.johnkim.app.mobile.util.MyHistoryCommon;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.orm.ibatis.support.SqlMapClientDaoSupport;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;

import javax.annotation.Resource;

/**
 * @author : johnkim <cale9797@gmail.com / Simple.ly Inc,>
 * @Date : 11. 12. 27
 */
//@Repository(value = "myHistoryMemberDao")
public class MyHistoryMemberDaoImpl extends SqlMapClientDaoSupport implements MyHistoryMemberDao {
    // SLF4J Logging
	private Logger logger = LoggerFactory.getLogger(MyHistoryMemberDaoImpl.class);
    private MyHistoryCommon myHistoryCommon;

//    private PlatformTransactionManager transactionManager;

    /**
     * 멤버 등록시 중복 확인을 한다.
     *
     * @param myHistoryMember
     * @return MyHistoryMember
     */
    public MyHistoryMember checkDuplication(MyHistoryMember myHistoryMember) {
        logger.info("checkDuplication");
        return (MyHistoryMember)getSqlMapClientTemplate().queryForObject("MYHISTORY_MEMBER.checkDuplication", myHistoryMember);
    }

    @Resource(name="transactionManager")
    protected DataSourceTransactionManager transactionManager;

    protected TransactionStatus getTransaction() {
        DefaultTransactionDefinition definition = new DefaultTransactionDefinition();
        definition.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
        return transactionManager.getTransaction(definition);
    }

    /**
     * 멤버를 등록 한다.
     *
     * 사용자를 등록 하면서 Dayve 에서 제공 하는 Group, Category, Item 을 같이 등록 한다.
     *
     * 1. 사용자를 등록 한다.
     * 2. 미리 정의된 Group 목록을 등록 한다.
     * 3. Group 목록에서 Group 명을 가져 와서 Category 목록을 등록 한다.
     * 4. Category 목록을 가져 와서 Category 명으로 Item 목록을 등록 한다.
     *
     *
     * @param myHistoryMember
     * @return True or False
     */
    @Override
    public boolean registerMember(MyHistoryMember myHistoryMember) {
        logger.info("registerMember");

        boolean result = false;

//        myHistoryCommon = new MyHistoryCommon();
//
//        MyHistoryGroup myHistoryGroup = new MyHistoryGroup();
//        myHistoryGroup.setOpenGroupYn("N");
//        myHistoryGroup.setFavoriteYn("N");
//        myHistoryGroup.setActivateYn("Y");
//        myHistoryGroup.setModifyDate(myHistoryMember.getModifyDate());
//        myHistoryGroup.setRegisterDate(myHistoryMember.getRegisterDate());
//        myHistoryGroup.setMyHistoryMembersId(myHistoryMember.getId());
//
//        MyHistoryGroupDaoImpl myHistoryGroupDao = new MyHistoryGroupDaoImpl();
//        List<MyHistoryGroup> groupList = new ArrayList<MyHistoryGroup>();


//        TransactionStatus transactionStatus = getTransaction();



//        TransactionStatus transactionStatus = transactionManager.getTransaction(new DefaultTransactionDefinition());

        

        try {
            // 사용자 정보를 등록 한다.
            getSqlMapClientTemplate().insert("MYHISTORY_MEMBER.registerMember", myHistoryMember);
            // 미리 정의된 Group 목록을 등록 한다.
//            getSqlMapClientTemplate().insert("MYHISTORY_GROUP.registerGroupList", myHistoryGroup);
//
//
//            // 등록한 사용자의 group 목록을 가져 온다.
//            groupList = myHistoryGroupDao.selectGroupList(myHistoryGroup);
//
//            for(int i=0 ; i<groupList.size() ; i++) {
//                if(("FOOD").equals(groupList.get(i).getName())) {
//                    MyHistoryCategory myHistoryCategory = new MyHistoryCategory();
//                    myHistoryCategory.setOpenCategoryYn("N");
//                    myHistoryCategory.setFavoriteYn("N");
//                    myHistoryCategory.setActivateYn("Y");
//                    myHistoryCategory.setModifyDate(myHistoryMember.getModifyDate());
//                    myHistoryCategory.setRegisterDate(myHistoryMember.getRegisterDate());
//                    myHistoryCategory.setGroupName(groupList.get(i).getName());
//                    myHistoryCategory.setGroupUnit("GENERAL");
//                    myHistoryCategory.setGroupUnitTime("");
//                    myHistoryCategory.setMyHistoryMembersId(myHistoryMember.getId());
//                    myHistoryCategory.setMyHistoryGroupsIdMyHistoryGroups(groupList.get(i).getIdMyHistoryGroups());
//
//                    // category 목록 등록.
//
//                } else if(("DRINK").equals(groupList.get(i).getName())) {
//
//                }
//            }
            


            logger.info("Success to register member.");

            result = true;
        } catch (Exception e) {
//            transactionManager.rollback(transactionStatus);

//            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();

            result = false;

            logger.error("Fail to register member.");

            /**
             * 만약 group 이나 category 나 item 등록시 하나 라도 오류가 발생 하면
             * 사용자 삭제 하는 로직 추가 해야 함.
             */
        }

//        transactionManager.commit(transactionStatus);

        return result;
    }

    /**
     * 멤버 로그인을 한다.
     *
     * @param myHistoryMember
     * @return MyHistoryMember
     */
    public MyHistoryMember login(MyHistoryMember myHistoryMember) {
        logger.info("login");
        return (MyHistoryMember)getSqlMapClientTemplate().queryForObject("MYHISTORY_MEMBER.login", myHistoryMember);
    }

    /**
     * 멤버 정보를 수정 한다.
     *
     * @param myHistoryMember
     * @return
     */
    public boolean updateMember(MyHistoryMember myHistoryMember) {
        logger.info("updateMember");

        boolean result = false;

        try {
            getSqlMapClientTemplate().update("MYHISTORY_MEMBER.updateMember", myHistoryMember);
            result = true;
        } catch (Exception e) {
            result = false;
        }

        return result;
    }

    /**
     * 멤버를 비활성화 한다.
     *
     * @param myHistoryMember
     * @return
     */
    public boolean updateDeactivateMember(MyHistoryMember myHistoryMember) {
        logger.info("updateDeactivateMember");

        boolean result = false;

        try {
            getSqlMapClientTemplate().update("MYHISTORY_MEMBER.updateDeactivateMember", myHistoryMember);
            result = true;
        } catch (Exception e) {
            result = false;
        }

        return result;
    }

    /**
     * 사용자의 마일리지를 가져 온다.
     *
     * @param myHistoryMember
     * @return
     */
    public MyHistoryMember selectMileage(MyHistoryMember myHistoryMember) { 
        logger.info("selectMileage");
        return (MyHistoryMember)getSqlMapClientTemplate().queryForObject("MYHISTORY_MEMBER.selectMileage", myHistoryMember);
    }

    /**
     * 마일리지를 업데이트(추가) 한다.
     *
     * @param myHistoryMember
     * @return
     */
    public boolean updateMileage(MyHistoryMember myHistoryMember) {
        logger.info("updateMileage");

        boolean result = false;

        try {
            getSqlMapClientTemplate().update("MYHISTORY_MEMBER.updateMileage", myHistoryMember);
            result = true;
        } catch (Exception e) {
            result = false;
        }

        return result;
    }

    /**
     * 사용자 비밀번호를 변경 한다.
     *
     * @param myHistoryMember
     * @return
     */
    @Override
    public boolean updatePassword(MyHistoryMember myHistoryMember) {
        logger.info("updatePassword");

        boolean result = false;

        try {
            getSqlMapClientTemplate().update("MYHISTORY_MEMBER.updatePassword", myHistoryMember);
            result = true;
        } catch (Exception e) {
            result = false;
        }

        return result;
    }

    /**
     * 사용자 이메일을 업데이트 한다.
     *
     * @param myHistoryMember
     * @return
     */
    @Override
    public boolean updateEmail(MyHistoryMember myHistoryMember) {
        logger.info("updateEmail");

        boolean result = false;

        try {
            getSqlMapClientTemplate().update("MYHISTORY_MEMBER.updateEmail", myHistoryMember);
            result = true;
        } catch (Exception e) {
            result = false;
        }

        return result;
    }


}
